const {
	Controller
} = require('uni-cloud-router')
const uniID = require('uni-id')
const dbHelper = require('db-helper')
module.exports = class UserController extends Controller {
	async login() {
		const {
			username,
			password
		} = this.ctx.data
		console.log('login', username, password)
		let loginRes = await this.service.user.login({
			username,
			password
		})
		if (loginRes.code) {
			return loginRes
		}
		let isBoss = loginRes.userInfo.role.some(item => {return item === "boss"})
		let isEmployee = loginRes.userInfo.role.some(item => {return item === "employee" || item === "employee_2"})
		if (isBoss) {
			let stores = await dbHelper.getList("t3ds-store", {
				uid: loginRes.uid
			})
			if (!stores.length) {
				await uniID.logout(loginRes.token)
				return {
					code: 500,
					message: '未配置门店，请联系客服'
				}
			}
			loginRes.store = stores[0]
			loginRes.stores = stores
		} else if (isEmployee) {
			let stores = await dbHelper.getList("t3ds-store", {
				employeeIds: loginRes.uid
			})
			if (!stores.length) {
				await uniID.logout(loginRes.token)
				return {
					code: 500,
					message: '未配置门店，请联系客服'
				}
			}
			// else if (stores.length > 1) {
			// 	await uniID.logout(loginRes.token)
			// 	return {
			// 		code: 500,
			// 		message: '员工账号配置了多个门店，请联系客服'
			// 	}
			// }
			loginRes.store = stores[0]
			loginRes.stores = stores
		}
		return loginRes
	}

	async register() {
		const {
			username,
			password
		} = this.ctx.data
		const admin = await this.service.user.hasAdmin()
		if (admin) {
			return {
				code: 10001,
				message: '超级管理员已存在，请登录...'
			}
		}
		return uniID.register({
			username,
			password,
			role: ["admin"]
		})
	}

	async logout() {
		return this.service.user.logout(this.ctx.event.uniIdToken)
	}

	async getUserInfoById() {
		let {
			id,
			_id
		} = this.ctx.data
		if (!id && !_id) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		try{
			let user = await this.service.user.getUserInfoById({
				id,
				_id
			})
			return {
				code: 200,
				result: user
			}
		}catch(e){
			return {
				code: 500,
				msg: e.message
			}
		}
	}
}